package ast;

import java.io.PrintStream;
import java.util.Map;
import java.util.Scanner;
import java.util.Stack;

public class Decl extends Unit {
	public final VarDecl varDecl;
	public final Expr expr;

	public Decl(VarDecl d, Location loc) {
		super(loc);
		varDecl = d;
		expr = null;
	}

	public Decl(VarDecl d, Expr e, Location loc) {
		super(loc);
		varDecl = d;
		expr = e;
	}

	public void print(PrintStream ps, String indent) {
		ps.print(indent);
		varDecl.print(ps);
		if (expr != null) {
			ps.print(" = ");
			expr.print(ps);
		}
		ps.print(";");
	}

	public void print(PrintStream ps) {
		print(ps, "");
	}

	// intepret: if expr is not null, then interpret expr and put the result in the state map
	// if expr is null, then put null in the state map, TODO: this will be handled when the identExpr is evaluated
	public void execute(Stack<Map<String, AbstractValue>> stateStack, Scanner scanner) throws Exception {
		if (expr != null) {
			stateStack.peek().put(varDecl.ident, expr.evaluate(stateStack, scanner));
		} else {
			// IMPORTANT: if "int x;", then x is not initialized. This has to be handled in identExpr.
			stateStack.peek().put(varDecl.ident, null);
		}
		return;
	}
}
